import json
import logging
from fastapi import APIRouter, Depends, HTTPException, Request
from datetime import datetime, timedelta
from typing import Annotated
from decimal import Decimal
from tortoise.transactions import in_transaction

from models.enums import OrderStatus, PaymentStatus, PaymentChannel
from models.user import User
from models.payment import Payment, OrderFake, OrderItemFake
from schemas.payment_schemas import *
from utils.pay.ali_service import AlipayService
from utils.pay.wechatpay import WechatPayService  
# from utils.pay.unionpay import UnionPayService  # 预留银联支付

# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/payment", tags=["支付模块"])

alipay_service = AlipayService()
wechatpay_service = WechatPayService()  # 预留微信支付
# unionpay_service = UnionPayService()  # 预留银联支付

##### 订单详情页点击"去支付"：创建支付记录 #####
@router.post("/create/{order_id}")
async def create_payment(order_id: int,request: Request):
    """订单详情页点击"去支付"：创建支付记录"""
    # 1. 验证用户+订单状态（必须是待支付且未创建支付记录）
    username = request.state.username
    if not username:
        # token 验证失败    
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    order = await OrderFake.get_or_none(
        id=order_id,
        user=user,
        status=OrderStatus.PENDING  # 仅待支付订单可创建支付记录
    )
    if not order:
        raise HTTPException(status_code=400, detail="订单状态异常，无法支付")
    
    # 2. 检查是否已存在有效支付记录（防止重复创建）
    existing_payment = await Payment.filter(
        order=order,
        pay_status=PaymentStatus.PENDING  # 待支付可复用（创建好支付记录表之后没有立即扫码支付，而是离开了当前页面）
    ).first()
    if existing_payment:
        return {
            "code": 200,
            "message": "支付记录已经创建",
            "data": {
                "payment_id": existing_payment.id,
                "order_id": order.id,
                "expire_time": existing_payment.timeout_at.isoformat()
            }
        }
    
    # 3. 创建支付记录（10分钟超时）
    payment = await Payment.create(
        order=order,
        pay_amount=order.actual_amount,
        pay_channel=order.payment_channel,
        pay_status=PaymentStatus.PENDING,
        timeout_at=datetime.now() + timedelta(minutes=10)
    )
    
    return {
        "code": 200,
        "message": "支付记录创建成功",
        "data": {
            "payment_id": payment.id,
            "order_id": order.id,
            "expire_time": payment.timeout_at.isoformat(),
            "total_amount": float(payment.pay_amount)
        }
    }

##### 支付宝支付 #####
@router.post("/alipay/{payment_id}")
async def alipay_pay(payment_id: int, request: Request):
    """支付宝支付：基于支付记录生成支付链接"""
    username = request.state.username
    if not username:
        # token 验证失败    
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    
    # 验证支付记录归属+状态，动态构建查询条件
    # 执行流程
        # 首先执行子查询 OrderFake.filter(...).values_list(...)，获取指定用户的所有订单 ID。
        # 然后执行主查询 Payment.get_or_none(...)，结合三个条件过滤出符合要求的支付记录。
        # 最后使用 prefetch_related 预加载关联的订单对象，以便后续可以直接访问订单信息而无需再次查询数据库。
    # 先执行查询，获取订单ID列表    
    order_ids = await OrderFake.filter(user=user).values_list("id", flat=True)
    print('order_ids: ', order_ids)
    payment = await Payment.get_or_none(
        id=payment_id,
        order_id__in=order_ids,
        pay_status=PaymentStatus.PENDING,
        pay_channel=PaymentChannel.ALIPAY
    ).prefetch_related("order")  
     
    if not payment:
        raise HTTPException(status_code=400, detail="支付记录异常")
    
    # 生成支付宝支付链接
    subject = f"支付订单: {payment.order.order_number}"
    payment_url = alipay_service.create_payment(
        out_trade_no=payment.order.order_number,  # 订单号
        total_amount=float(payment.order.actual_amount),  # 实际支付金额
        subject=subject
    )
    
    return {
        "code": 200,
        "message": "支付宝支付链接生成成功",
        "data": {
            "payment_url": payment_url,  # 支付宝支付页链接
        }
    }

##### 余额支付 #####
@router.post("/balance/{payment_id}")
async def balance_pay(payment_id: int, request: Request):
    """余额支付：直接扣减余额并更新状态"""
    username = request.state.username
    if not username:
        # token 验证失败    
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)

    # 验证支付记录，动态构建查询条件
    order_ids = await OrderFake.filter(user=user).values_list("id", flat=True)
    payment = await Payment.get_or_none(
        id=payment_id,
        order_id__in=order_ids,
        pay_status=PaymentStatus.PENDING
    ).prefetch_related("order")
    if not payment:
        raise HTTPException(status_code=400, detail="支付记录异常")
    
    # 校验余额
    if user.balance < payment.pay_amount:
        raise HTTPException(status_code=400, detail="余额不足，请充值")
    
    # 事务：扣减余额+更新状态
    async with in_transaction():
        # 扣减余额
        user.balance -= payment.pay_amount
        await user.save()
        
        # 更新支付记录和订单状态
        await payment.update_status(PaymentStatus.PAID)
        
        order = await payment.order
        
        # 确认扣减库存（从"锁定"变为实际扣减）
        
        items = await OrderItemFake.filter(order=order).prefetch_related("product")
        for item in items:
            product = await item.product
            product.inventory -= item.quantity  # 扣减库存（实际上这一步应该是在创建订单表那里进行）
            product.sales += item.quantity  # 增加销量
            await product.save()
    
    return {"code": 200, "message": "余额支付成功"}


##### 通用支付接口 #####
@router.post("/pay/{payment_id}")
async def pay(payment_id: int, request: Request):
    """根据支付渠道调用相应的支付接口"""
    username = request.state.username
    if not username:
        raise HTTPException(status_code=401, detail="用户未登录")
    
    user = await User.get_or_none(username=username)
    
    # 验证支付记录
    order_ids = await OrderFake.filter(user=user).values_list("id", flat=True)
    print('order_ids: ', order_ids)
    payment = await Payment.get_or_none(
        id=payment_id,
        order_id__in=order_ids,
        pay_status=PaymentStatus.PENDING
    ).prefetch_related("order")
    
    if not payment:
        raise HTTPException(status_code=400, detail="支付记录不存在或状态异常")
    
    order = payment.order
    
    if payment.pay_channel == PaymentChannel.WECHAT:
        # 微信支付
        result = wechatpay_service.create_native_payment(
            out_trade_no=order.order_number,
            total_amount=int(payment.pay_amount * 100),  # 转为分
            description=f"订单支付: {order.order_number}"
        )
        print('微信支付的结果:', result)
        logger.info('微信支付生成的链接参数',result)
        if result["code"] != 200:
            raise HTTPException(status_code=400, detail=result["message"])
        code_url = result["data"]["code_url"]
        
        return {
            "code": 200,
            "message": "微信支付二维码链接生成成功",
            "data": {
                "payment_id": payment_id,
                "order_id": order.id,
                "out_trade_no": order.order_number,
                "total_amount": float(payment.pay_amount),
                "code_url": code_url,
                "expire_time": payment.timeout_at.isoformat()
            }
        }
    elif payment.pay_channel == PaymentChannel.ALIPAY:
        # 支付宝支付
        subject = f"支付订单: {order.order_number}"
        payment_url = alipay_service.create_payment(
            out_trade_no=order.order_number,
            total_amount=float(payment.pay_amount),
            subject=subject
        )
        
        return {
            "code": 200,
            "message": "支付宝支付链接生成成功",
            "data": {
                "payment_id": payment_id,
                "order_id": order.id,
                "payment_url": payment_url,
                "expire_time": payment.timeout_at.isoformat()
            }
        }
    elif payment.pay_channel == PaymentChannel.BALANCE:
        # 余额支付
        if user.balance < payment.pay_amount:
            raise HTTPException(status_code=400, detail="余额不足")
        
        async with in_transaction():
            # 扣减余额
            user.balance -= payment.pay_amount
            await user.save()
            
            # 更新支付记录
            payment.pay_status = PaymentStatus.PAID
            payment.pay_time = datetime.now()
            await payment.save()
            
            # 更新订单状态
            order.status = OrderStatus.PAID
            await order.save()
            
            # 扣减库存
            items = await OrderItemFake.filter(order=order).prefetch_related("product")
            for item in items:
                product = await item.product
                if product.inventory < item.quantity:
                    # 库存不足
                    return {
                        "code": 400,
                        "message": "订单中的商品有库存不足的，请修改后重试",
                    }  
                product.inventory -= item.quantity
                product.sales += item.quantity
                await product.save()
        
        return {
            "code": 200,
            "message": "余额支付成功",
            "data": {
                "payment_id": payment_id,
                "order_id": order.id,
                "out_trade_no": order.order_number,
                "total_amount": float(payment.pay_amount),
                "status": "PAID"
            }
        }
    else:
        raise HTTPException(status_code=400, detail="不支持的支付渠道")


# 重新支付
@router.post("/repay/{order_id}")
async def repay(order_id: int, request: Request):
    """订单详情页"重新支付"：支付失败后重新创建支付记录"""
    username = request.state.username
    if not username:
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    order = await OrderFake.get_or_none(
        id=order_id,
        user=user,
        status=OrderStatus.PENDING  # 仅待支付订单可重新支付
    )
    if not order:
        raise HTTPException(status_code=400, detail="仅待支付订单可重新支付")
    
    # 检查是否有支付失败记录
    failed_payment = await Payment.filter(
        order=order,
        pay_status=PaymentStatus.FAILED
    ).first()
    if not failed_payment:
        raise HTTPException(status_code=400, detail="无支付失败记录")
    
    # 调用支付记录创建接口（复用逻辑）
    return await create_payment(order_id, request)

# 取消订单（用户主动取消的逻辑——两种情况：第一种是支付记录还未创建，第二种是支付记录已创建且还是待支付状态）
@router.post("/order/cancel/{order_id}")
async def cancel_order(order_id: int, request: Request):
    username = request.state.username
    if not username:
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    order = await OrderFake.get_or_none(
        id=order_id,
        user=user,
        status=OrderStatus.PENDING  # 仅待支付可取消
    )
    if not order:
        raise HTTPException(status_code=400, detail="仅待支付订单可取消")
    
    async with in_transaction():
        # 1. 更新订单状态
        order.status = OrderStatus.CANCELLED
        order.cancelled_at = datetime.now()
        await order.save()
        
        # 2. 处理支付记录（若已创建）
        existing_payment = await Payment.filter(
            order=order,
            pay_status=PaymentStatus.PENDING  # 仅取消待支付的支付记录
        ).first()
        if existing_payment:
            existing_payment.pay_status = PaymentStatus.CANCELLED
            await existing_payment.save()
        
        # 3. 释放库存
        items = await OrderItemFake.filter(order=order).prefetch_related("product")
        for item in items:
            product = await item.product
            product.inventory += item.quantity  # 回滚库存
            await product.save()
    
    return {"code": 200, "message": "订单已取消"}

# 获取支付状态
@router.get("/status/{order_id}")
async def get_payment_status(order_id: int, request: Request):
    """订单详情页轮询：获取支付状态"""
    username = request.state.username
    if not username:
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    order = await OrderFake.get_or_none(id=order_id, user=user)
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 获取最新支付记录
    payment = await Payment.filter(order=order).order_by("-created_at").first()
    return {
        "code": 200,
        "message": "获取支付状态成功",
        "data": {
            "user_id": user.id,
            "username": user.username,
            "order_id": order.id,
            "order_number": order.order_number,
            "paid_at": order.paid_at if order.status == OrderStatus.PAID else None,
            "payment_id": payment.id if payment else None,
            "pay_amount": f"{payment.pay_amount:.2f}" if payment else None,  # 格式化成两位小数的字符串形式
            "pay_number": payment.pay_number if payment else None,
            "pay_channel": payment.pay_channel if payment else None,
            "transaction_id": payment.transaction_id if payment.transaction_id else None,
            "pay_channel": payment.pay_channel if payment else None,
            "order_status": order.status,
            "payment_status": payment.pay_status if payment else None,
            "expire_time": payment.timeout_at.isoformat() if (payment and payment.pay_status == PaymentStatus.PENDING) else None
        }
    }

# 根据订单编号查询订单的支付状态
@router.post("/payment_status/{order_number}")
async def payment_status_by_order(order_number: str, request: Request):
    """根据订单号查询支付状态的接口"""
    username = request.state.username
    if not username:
        raise HTTPException(status_code=401, detail="用户未登录")
    user = await User.get_or_none(username=username)
    
    order = await OrderFake.get_or_none(order_number=order_number)
    print("本地订单",order)
    if not order:
        logger.error(f"沙箱支付关联订单不存在: {order_number}")
        return {'code': 404, 'message': '支付订单不存在'}
    # 查询本地支付信息是否存在
    payment = await Payment.get_or_none(order=order)
    print("订单的支付记录",payment)
    if not payment:
        logger.error(f"沙箱支付关联支付订单不存在: {order_number}")
        return {'code': 404, 'message': '支付信息不存在'}
    
    if order.payment_channel == 'alipay':
        # 沙箱支付宝  根据订单号查询沙箱数据
        result = alipay_service.query_payment(order_number)
        trade_status = result.get("trade_status")
        print("根据订单号查询结果",result)
        print("根据订单号查询到的交易状态：",trade_status)
        
        if trade_status == 'TRADE_SUCCESS' or trade_status == 'TRADE_FINISHED':
            # 交易成功，更新订单和支付状态
            logger.info(f"沙箱支付关联订单号 {order_number} 支付成功")
            if order.status != OrderStatus.PAID:
                await order.update_status(OrderStatus.PAID)
                if payment.pay_status != PaymentStatus.PAID:
                    payment.pay_status = PaymentStatus.PAID
                    payment.transaction_id = result["trade_no"]
                    payment.updated_at = datetime.now()
                    await payment.save()
                # 扣减库存
                order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
                for item in order_items:
                    product = await item.product
                    product.inventory -= item.quantity
                    product.sales += item.quantity
                    await product.save()

            return {'code': 200, 
                    'message': '订单支付成功', 
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'transaction_id': result["trade_no"],
                        "amount": f"{order.actual_amount:.2f}",
                        'pay_channel': order.payment_channel,
                        'payment_status': PaymentStatus.PAID,
                        'order_status': OrderStatus.PAID,
                        'paid_at': order.paid_at,
                    }}
                            
        elif trade_status == 'TRADE_FAILED':
            if payment.pay_status == PaymentStatus.PENDING and order.status == OrderStatus.PENDING:
                await payment.update_status(PaymentStatus.FAILED)
                return {
                    'code': 400, 
                    'message': '支付失败',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.FAILED,
                        'order_status': OrderStatus.PENDING,
                    }
                }
        # 如果支付宝返回的订单状态是关闭，如果支付状态是未付款，分为交易超时和用户主动取消两种情况
        elif trade_status == 'TRADE_CLOSED':
            # 如果支付状态是未付款，且交易关闭时间超过了设置的超时时间未付款
            if payment.pay_status == PaymentStatus.PENDING and datetime.now() >= payment.timeout_at:
                await payment.update_status(PaymentStatus.TIMEOUT)
                return {
                    'code': 400, 
                    'message': '支付超时',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.TIMEOUT,
                        'order_status': OrderStatus.CANCELLED,
                    }
                }
            else:
                # 用户主动取消
                await order.update_status(OrderStatus.CANCELLED)
                return {
                    'code': 400, 
                    'message': '订单已取消',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.CANCELLED,
                        'order_status': OrderStatus.CANCELLED,
                    }
                }
    elif order.payment_channel == 'wechat':
        # 微信支付根据订单号查询订单状态
        result = wechatpay_service.query_order(order_number)
        print('result')
        if result["code"] == 200:
            trade_state = result["data"]["trade_state"]
        else:
            return {'code': 400, "meassage": "订单查询失败"}
        if trade_state == "SUCCESS":
            # 交易成功，更新订单和支付状态
            logger.info(f"微信支付关联订单号 {order_number} 支付成功")
            if order.status != OrderStatus.PAID:
                await order.update_status(OrderStatus.PAID)
                if payment.pay_status != PaymentStatus.PAID:
                    payment.pay_status = PaymentStatus.PAID
                    payment.updated_at = datetime.now()
                    await payment.save()
                # 扣减库存
                order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
                for item in order_items:
                    product = await item.product
                    product.inventory -= item.quantity
                    product.sales += item.quantity
                    await product.save()
                    
            return {'code': 200, 
                    'message': '订单支付成功', 
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        "amount": f"{order.actual_amount:.2f}",
                        'pay_channel': order.payment_channel,
                        'payment_status': PaymentStatus.PAID,
                        'order_status': OrderStatus.PAID,
                        'paid_at': order.paid_at,
                    }}
        elif trade_state == "NOTPAY":
            if payment.pay_status == PaymentStatus.PENDING and order.status == OrderStatus.PENDING:
                return {
                    'code': 400, 
                    'message': '订单未支付',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.PENDING,
                        'order_status': OrderStatus.PENDING,
                    }
                }  
            elif payment.pay_status == PaymentStatus.FAILED and order.status == OrderStatus.PENDING:
                await payment.update_status(PaymentStatus.FAILED)
                return {
                    'code': 400, 
                    'message': '支付失败',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.FAILED,
                        'order_status': OrderStatus.PENDING,
                    }
                }  
        # 如果交易关闭，用户主动取消或者系统超时取消
        elif trade_state == "CLOSED":
            # 如果支付状态是未付款，且交易关闭时间超过了设置的超时时间未付款
            if payment.pay_status == PaymentStatus.PENDING and datetime.now() >= payment.timeout_at:
                await payment.update_status(PaymentStatus.TIMEOUT)
                return {
                    'code': 400, 
                    'message': '支付超时',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.TIMEOUT,
                        'order_status': OrderStatus.CANCELLED,
                    }
                }
            else:
                # 用户主动取消
                await order.update_status(OrderStatus.CANCELLED)
                return {
                    'code': 400, 
                    'message': '订单已取消',
                    'data': {
                        'user_id': user.id,
                        'order_number': order_number,
                        'payment_status': PaymentStatus.CANCELLED,
                        'order_status': OrderStatus.CANCELLED,
                    }
                }   
    elif order.payment_channel == 'balance':
        # 如果使用余额支付，直接完成支付
        logger.info(f"余额支付关联订单号 {order_number} 支付成功")
        if order.status != OrderStatus.PAID:
            return {
                'code': 400,
                'message': '余额支付失败'
            }
        else:
            return {
                'code': 200, 
                'message': '余额支付成功', 
                'data': {
                    'user_id': user.id,
                    'order_number': order_number,
                    "amount": f"{order.actual_amount:.2f}",
                    'pay_channel': order.payment_channel,
                    'payment_status': PaymentStatus.PAID,
                    'order_status': OrderStatus.PAID,
                    'paid_at': order.paid_at,
                }}
            
    # 如果没有匹配到支渠道，返回失败
    else:
        return {'code': 400, 'message': '支付渠道无效'}

# 沙箱环境下异步通知
@router.api_route("/alipay/sandbox_notify",methods=['GET','POST'])
async def alipay_notify(request: Request):
    """支付宝同步/异步通知处理
    http://t38c5862.natappfree.cc/payment/sandbox_result?charset=utf-8&out_trade_no=ORDER7356131115586949120&method=alipay.trade.page.pay.return&total_amount=16.00&sign=Ccpw9FMuXuC0u9bY2DtIrk2EW%2BERtNKCpsezH9B23dRAxInnJt5Av9GZEGqli6bAF6NHp3r6rhlwVuIlTa7ZRHJMVxlyslskX4esOhtODbw9dsdrEWXmJ%2F%2BKugB1gnUDDH2g1CnWE%2BQ%2FN7iexN5sfIVGk3R4AXTiOGFy6myWhSTQxUMXVY3%2B288AGuoyhBZEkAdFMnr8eTTX9ka9kc%2F4hpdsUo9mZly0LcKjT4jHHwT%2FmS5XOJOjEsXiTm5VvHRhyHCg7KNQQC7IzKfctnJKOvB9nXIHKrJLhqV9Z9y7UM%2BeKQRQ3Wxx0Xe9eKmkpE%2BLg9ZdqGOdrYwxe9K1cADu9g%3D%3D&trade_no=2025073022001401120506107667&auth_app_id=9021000150667921&version=1.0&app_id=9021000150667921&sign_type=RSA2&seller_id=2088721074001114&timestamp=2025-07-30+09%3A22%3A17
    """
    if request.method=='GET':
        # 1. 接收原始查询数据
        data_dict = dict(request.query_params)
        print("沙箱的同步数据",data_dict)
        if data_dict:
            logger.info(f"沙箱支付同步通知数据: {data_dict}")
        # 2. 验证签名
        if not alipay_service.verify_notification(data_dict.copy()):
            logger.error("沙箱支付同步状态验证失败")
            return {"code": "400", "message": "同步状态验证失败"}
        # 3. 获取订单信息
        out_trade_no = data_dict.get("out_trade_no")
        trade_status = data_dict.get("trade_status")
        print("本地沙箱返回的支付状态",trade_status)
        if not out_trade_no:
            return {"code": 400, "message": "缺少订单号"}
        print("支付成功后订单号",out_trade_no)

        # 4. 查询本地订单是否存在
        order = await OrderFake.get_or_none(order_number=out_trade_no)
        print("本地订单",order)
        if not order:
            logger.error(f"沙箱支付关联订单不存在: {out_trade_no}")
            return {'code': 404, 'message': '支付订单不存在'}
        # 5. 查询本地支付信息是否存在
        payment = await Payment.get_or_none(order=order)
        print("订单的支付记录",payment)
        if not payment:
            logger.error(f"沙箱支付关联支付订单不存在: {out_trade_no}")
            return {'code': 404, 'message': '支付信息不存在'}
        # 6. 根据交易状态修改本地订单和支付信息状态
        try:
            # 6.1 如果支付宝返回的订单状态是已支付或者已完成（交易成功），将本地状态修改为已支付
            if trade_status == 'TRADE_SUCCESS' or trade_status == 'TRADE_FINISHED':
                return {'code': 200, 'payment_id':payment.id,'message': '支付成功'}
            # 6.2 如果支付宝返回的订单状态是交易失败，如果支付状态是未付款且订单状态也是未付款，修改为支付失败 
            elif trade_status == 'TRADE_FAILED':
                return {'code': 400, 'message': '支付失败'}
            # 6.3 如果支付宝返回的订单状态是关闭，如果支付状态是未付款，分为交易超时和用户主动取消两种情况
            elif trade_status == 'TRADE_CLOSED':
                # 6.3.1 如果支付状态是未付款，且交易关闭时间超过了设置的超时时间未付款
                if payment.pay_status == PaymentStatus.PENDING and datetime.now() >= payment.timeout_at:
                    return {'code': 400, 'message': '支付超时'}
                else:
                    # 用户主动取消
                    return {'code': 400, 'message': '支付已取消'}
        except Exception as e:
            logger.exception(f"沙箱支付处理异常: {e}")
            return {'code': 400, 'message': '支付处理异常'}
    elif request.method=='POST':
        try:
            # 1. 接收原始表单数据
            # print("沙箱的返回参数》》》》》", request.query_params)
            # data_dict = dict(request.query_params)
            
            # 记录请求头
            headers = dict(request.headers)
            print(f"请求头: {headers}")
            
            # 记录请求体（根据 Content-Type 处理）
            content_type = headers.get("content-type", "")
            
            if "application/x-www-form-urlencoded" in content_type:
                # 表单数据
                data = await request.form()
                print(f"表单数据: {dict(data)}")
            elif "application/json" in content_type:
                # JSON 数据
                data = await request.json()
                print(f"JSON 数据: {data}")
            elif "text/xml" in content_type:
                # XML 数据
                data = await request.body()
                print(f"XML 数据: {data.decode('utf-8')}")
            else:
                # 其他格式
                data = await request.query_params
                print(f"原始数据: {data}")
            data_dict = dict(data) 
            logger.info(f"支付宝异步通知数据: {data_dict}")
            
            # 2. 验证签名
            # 这里需要调用支付宝SDK的verify方法验证签名
            # 已经有alipay_service.verify_notification方法
            if not alipay_service.verify_notification(data_dict.copy()):
                logger.error("支付宝异步通知签名验证失败")
                return "fail"  # 签名验证失败
            
            # 3. 验证必传参数
            required_fields = ["out_trade_no", "trade_no", "total_amount", "trade_status"]
            for field in required_fields:
                if field not in data_dict:
                    logger.error(f"支付宝异步通知缺少必传参数: {field}")
                    return "fail"  # 缺少必传参数
            
            # 4. 关联本地订单和支付记录
            order_number = data_dict["out_trade_no"]
            order = await OrderFake.get_or_none(order_number=order_number)
            if not order:
                logger.error(f"支付宝异步通知关联订单不存在: {order_number}")
                return "fail"  # 订单不存在
            
            payment = await Payment.get_or_none(order=order)
            if not payment:
                logger.error(f"支付宝异步通知关联支付记录不存在: {order_number}")
                return "fail"  # 支付记录不存在
            
            # 5. 验证金额一致性
            if Decimal(data_dict["total_amount"]) != order.actual_amount:
                logger.error(f"支付宝异步通知金额不一致: {order_number}")
                return "fail"  # 金额不一致
            
            # 6. 处理交易状态（事务处理）
            async with in_transaction():
                trade_status = data_dict["trade_status"]
                logger.info(f"支付宝异步通知交易状态: {trade_status}")
                
                if trade_status in ["TRADE_SUCCESS", "TRADE_FINISHED"]:
                    # 支付成功
                    if order.status != OrderStatus.PAID:
                        order.status = OrderStatus.PAID
                        order.paid_at = datetime.now()
                        await order.save()
                    
                    if payment.pay_status != PaymentStatus.PAID:
                        payment.pay_status = PaymentStatus.PAID
                        payment.transaction_id = data_dict["trade_no"]
                        payment.updated_at = datetime.now()
                        await payment.save()
                    
                    # 扣减库存
                    order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
                    for item in order_items:
                        product = await item.product
                        product.inventory -= item.quantity
                        product.sales += item.quantity
                        await product.save()
                        
                elif trade_status == "TRADE_CLOSED":
                    # 交易关闭（支付超时或用户主动取消）
                    if payment.pay_status == PaymentStatus.PENDING and datetime.now() >= payment.timeout_at:
                        # 支付超时
                        await payment.update_status(PaymentStatus.TIMEOUT)
                    else:
                        # 用户主动取消
                        await order.update_status(OrderStatus.CANCELLED)
                    
                    # 释放库存
                    order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
                    for item in order_items:
                        product = await item.product
                        product.inventory += item.quantity
                        await product.save()
                        
                elif trade_status == "TRADE_FAILED":
                    # 交易失败
                    if payment.pay_status == PaymentStatus.PENDING:
                        payment.pay_status = PaymentStatus.FAILED
                        await payment.save()
            
            # 7. 返回成功标识
            logger.info(f"支付宝异步通知处理成功: {order_number}")
            return "success"
        except Exception as e:
            print("支付宝异步通知处理异常,原因是",e)
            logger.error("支付宝异步通知处理异常")
            return "fail"
    
# 微信异步通知
@router.post("/wechat/notify")
async def wechat_notify(request: Request):
    """微信支付异步通知处理"""
    try:
        # 1. 获取请求头和请求数据
        headers = dict(request.headers)
        data = await request.body()

        # 2. 验证签名
        verify_result = await wechatpay_service.verify_notification(headers, data)
        if not verify_result["success"]:
            logger.error("微信支付异步通知签名验证失败")
            return {"code": 400, "message": "签名验证失败"}

        # 3. 解析通知数据
        notify_data = json.loads(data.decode("utf-8"))
        out_trade_no = notify_data["out_trade_no"]
        transaction_id = notify_data["transaction_id"]
        trade_state = notify_data["trade_state"]

        # 4. 关联本地订单和支付记录
        order = await OrderFake.get_or_none(order_number=out_trade_no)
        if not order:
            logger.error(f"微信支付异步通知关联订单不存在: {out_trade_no}")
            return {"code": 400, "message": "订单不存在"}

        payment = await Payment.get_or_none(order=order)
        if not payment:
            logger.error(f"微信支付异步通知关联支付记录不存在: {out_trade_no}")
            return {"code": 400, "message": "支付记录不存在"}

        # 5. 处理交易状态
        if trade_state == "SUCCESS":
            # 支付成功
            if order.status != OrderStatus.PAID:
                order.status = OrderStatus.PAID
                order.paid_at = datetime.now()
                await order.save()

            if payment.pay_status != PaymentStatus.PAID:
                payment.pay_status = PaymentStatus.PAID
                payment.transaction_id = transaction_id
                payment.updated_at = datetime.now()
                await payment.save()

            # 扣减库存
            order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
            for item in order_items:
                product = await item.product
                product.inventory -= item.quantity
                product.sales += item.quantity
                await product.save()

        elif trade_state == "CLOSED":
            # 交易关闭（主动取消和超时自动取消两种情况）
            if payment.pay_status == PaymentStatus.PENDING:
                await payment.update_status(PaymentStatus.CANCELLED) 

            # 释放库存
            order_items = await OrderItemFake.filter(order=order).prefetch_related("product")
            for item in order_items:
                product = await item.product
                product.inventory += item.quantity
                await product.save()

        # 6. 返回成功标识
        logger.info(f"微信支付异步通知处理成功: {out_trade_no}")
        return {"code": 200, "message": "处理成功"}
    except Exception as e:
        logger.error("微信支付异步通知处理异常")
        return {"code": 500, "message": str(e)}
    

